/* eslint-disable no-unused-vars */
/* eslint-disable class-methods-use-this */
/* eslint-disable no-param-reassign */
/* eslint-disable import/no-cycle */
import {
  Button,
  Space,
  Form,
  Tabs,
  Radio,
  Input,
  Row,
  Col,
  Select,
  message,
  Checkbox,
  InputNumber,
  Popconfirm,
  Table,
} from 'antd';
import React from 'react';
import ApiHelper from '../api';
import DesignUtil from '../common/DesignUtil';
import BaseContainerControl from './BaseContainerControl';
import ControlPlus from './ControlPlus';
import ControlUtil from './ControlUtil';

const { TabPane } = Tabs;
const { Option } = Select;
/**
 * 分页容器控件
 */
class TableContainerControl extends BaseContainerControl {
  static create(props, dataProps, extProps) {
    return new TableContainerControl(props, dataProps, extProps);
  }

  constructor(props, dataProps, extProps) {
    const dataProps2 = {
      title: '表格控件',
      type: 'TableContainer',
      childControls: [],
      canAddChild: false,
      columns: [], // 列信息
      operators: [], // 操作信息
      page: { pagesize: 10 }, // 分页信息
      dataSource: '', // 数据源
      ...dataProps,
    };
    super(props, dataProps2, extProps);
    this.name = '表格';
    this.page = this.initPageValue();
    this.loading = false;
    this.dataSource = [];
    // this.icon = '';
  }

  init(parentForm) {
    super.init(parentForm);
    this.intSearch(parentForm);
    this.page = this.initPageValue();
    this.refreashData(parentForm);
  }

  // 重写 页面加载完成事件
  pageloaded(parentForm) {
    this.intSearch(parentForm);
    this.page = this.initPageValue();
    this.refreashData(parentForm);
  }

  // 重写 获取formItem控件的value值
  getJsonValue(jsonValues) {
    super.getJsonValue(jsonValues);
    const filters = [];
    this.data.columns.forEach((c) => {
      if (c.filter !== '') {
        const find = jsonValues.find((j) => j.key === `${c.key}_过滤`);
        filters.push(find);
      }
    });
    const orders = [];
    this.data.columns.forEach((c) => {
      if (c.order === true) {
        const find = jsonValues.find((j) => j.key === `${c.key}_排序`);
        orders.push(find);
      }
    });

    const value = { filters, orders, page: this.page };
    jsonValues.push({ key: this.data.key, title: this.data.title, value, type: this.data.type });
  }

  // 初始化page 值
  initPageValue() {
    return {
      current: 1,
      pageSize: this.data.page.pagesize,
      total: 0,
    };
  }

  // 初始化子控件
  initChildControls(parentForm) {
    const filterFlex = this.data.childControls.find((c) => c.data.key === `${this.data.key}_过滤`);
    if (filterFlex == null) {
      const c1 = ControlPlus.create('FlexContainer');
      c1.data.title = '过滤';
      c1.data.custom = false;
      c1.data.draggable = false;
      c1.data.canAddChild = false;
      c1.data.order = this.data.childControls.length + 1;
      c1.data.key = `${this.data.key}_过滤`;
      c1.init(parentForm);
      this.data.childControls = [...this.data.childControls, c1];
    }
    const orderFlex = this.data.childControls.find((c) => c.data.key === `${this.data.key}_排序`);
    if (orderFlex == null) {
      const c2 = ControlPlus.create('FlexContainer');
      c2.data.title = '排序';
      c2.data.custom = false;
      c2.data.draggable = false;
      c2.data.canAddChild = false;
      c2.data.order = this.data.childControls.length + 1;
      c2.data.key = `${this.data.key}_排序`;
      c2.init(parentForm);
      this.data.childControls = [...this.data.childControls, c2];
    }
  }

  // 初始化搜索过滤控件
  initFilterControls(parentForm) {
    const filterFlex = this.data.childControls.find((c) => c.data.key === `${this.data.key}_过滤`);
    const temp = filterFlex.data.childControls || [];
    filterFlex.data.childControls = [];
    this.data.columns.forEach((c) => {
      if (c.filter !== '') {
        const find = temp.find((t) => t.data.key === `${c.key}_过滤`);
        if (find != null) {
          find.data.title = c.name;
          filterFlex.data.childControls.push(find);
        } else {
          const c2 = ControlPlus.create(c.filter);
          c2.data.title = c.name;
          c2.data.custom = false;
          c2.data.draggable = false;
          c2.data.order = filterFlex.data.childControls.length + 1;
          c2.data.key = `${c.key}_过滤`;
          filterFlex.data.childControls.push(c2);
        }
      }
    });
  }

  // 初始化排序过滤控件
  initOrderControls(parentForm) {
    const orderFlex = this.data.childControls.find((c) => c.data.key === `${this.data.key}_排序`);
    const temp = orderFlex.data.childControls || [];
    orderFlex.data.childControls = [];
    this.data.columns.forEach((c) => {
      if (c.order === true) {
        const find = temp.find((t) => t.data.key === `${c.key}_排序`);
        if (find != null) {
          find.data.title = c.name;
          orderFlex.data.childControls.push(find);
        } else {
          const c2 = ControlPlus.create('Select');
          c2.data.title = c.name;
          c2.data.options = [
            { label: '无', value: '' },
            { label: '升序', value: 'asc' },
            { label: '降序', value: 'desc' },
          ];
          // c2.data.canEdit = false;
          c2.data.custom = false;
          c2.data.draggable = false;
          c2.data.order = orderFlex.data.childControls.length + 1;
          c2.data.key = `${c.key}_排序`;
          orderFlex.data.childControls.push(c2);
        }
      }
    });
  }

  // 初始化搜索栏
  intSearch(parentForm) {
    this.initChildControls(parentForm);
    this.initFilterControls(parentForm);
    this.initOrderControls(parentForm);
    parentForm.refreash();
  }

  getPropertyTabs(parentForm) {
    return [
      ...super.getPropertyTabs(parentForm),
      <TabPane tab="控件配置" key="3">
        <Form.Item label="列信息">
          <div>
            <Button
              type="link"
              onClick={() => {
                const column = { key: `列_${DesignUtil.UUID(16)}`, name: '', order: false, filter: '' };
                this.data.columns = [...this.data.columns, column];
                this.intSearch(parentForm);
              }}
            >
              添加
            </Button>
            <Row>
              <Col span={11}>列名</Col>
              <Col span={2}>排序</Col>
              <Col span={5}>过滤</Col>
              <Col span={3}>宽度 %</Col>
              <Col span={2}>操作</Col>
            </Row>
            {this.data.columns.map((c, index) => {
              const index2 = `cl:${index}_`;
              return (
                <Row key={index2}>
                  <Col span={11}>
                    <Input
                      placeholder="列名"
                      value={c.name}
                      onChange={(event) => {
                        c.name = event.target.value;
                        this.intSearch(parentForm);
                      }}
                    />
                  </Col>
                  <Col span={2}>
                    <Checkbox
                      checked={c.order}
                      onChange={(event) => {
                        c.order = event.target.checked;
                        this.intSearch(parentForm);
                      }}
                    />
                  </Col>
                  <Col span={5}>
                    <Select
                      value={c.filter}
                      onChange={(event) => {
                        c.filter = event;
                        this.intSearch(parentForm);
                      }}
                    >
                      <Select.Option value="">无</Select.Option>
                      <Select.Option value="Text">文本框</Select.Option>
                      <Select.Option value="Select">下拉框</Select.Option>
                    </Select>
                  </Col>
                  <Col span={3}>
                    <InputNumber
                      style={{ width: '50px' }}
                      min={0}
                      max={100}
                      defaultValue={0}
                      value={c.widthPercent}
                      onChange={(event) => {
                        c.widthPercent = event;
                        this.intSearch(parentForm);
                      }}
                    />
                  </Col>
                  <Col span={2}>
                    <Button
                      type="link"
                      onClick={() => {
                        DesignUtil.arrayRemove(this.data.columns, c);
                        this.intSearch(parentForm);
                      }}
                    >
                      删除
                    </Button>
                  </Col>
                </Row>
              );
            })}
          </div>
        </Form.Item>
        <Form.Item label="操作">
          <div>
            <Button
              type="link"
              onClick={() => {
                const operator = { key: `cl_${DesignUtil.UUID(16)}`, name: '', type: '', url: '' };
                this.data.operators = [...this.data.operators, operator];
                this.intSearch(parentForm);
              }}
            >
              添加
            </Button>
            <Row>
              <Col span={6}>文本</Col>
              <Col span={6}>类型</Col>
              <Col span={9}>网址</Col>
              <Col span={2}>操作</Col>
            </Row>
            {this.data.operators.map((c, index) => {
              const index2 = `op:${index}`;
              return (
                <Row key={index2}>
                  <Col span={6}>
                    <Input
                      placeholder="文本"
                      value={c.name}
                      onChange={(event) => {
                        c.name = event.target.value;
                        this.intSearch(parentForm);
                      }}
                    />
                  </Col>
                  <Col span={6}>
                    <Select
                      value={c.type}
                      onChange={(event) => {
                        c.type = event;
                        this.intSearch(parentForm);
                      }}
                    >
                      <Select.Option value="">无</Select.Option>
                      <Select.Option value="openurl">打开网址</Select.Option>
                      <Select.Option value="hrefurl">跳转网址</Select.Option>
                      <Select.Option value="confirm">确认操作</Select.Option>
                    </Select>
                  </Col>
                  <Col span={9}>
                    <Input
                      placeholder="网址"
                      value={c.url}
                      onChange={(event) => {
                        c.url = event.target.value;
                        this.intSearch(parentForm);
                      }}
                    />
                  </Col>
                  <Col span={2}>
                    <Button
                      type="link"
                      onClick={() => {
                        DesignUtil.arrayRemove(this.data.operators, c);
                        this.intSearch(parentForm);
                      }}
                    >
                      删除
                    </Button>
                  </Col>
                </Row>
              );
            })}
          </div>
        </Form.Item>
        <Form.Item label="数据源">
          <Select
            value={this.data.dataSource}
            onChange={(e) => {
              this.data.dataSource = e;
              this.intSearch(parentForm);
              this.page = this.initPageValue();
              this.refreashData(parentForm);
            }}
          >
            <Option value="">无</Option>
            {parentForm.dataSourceScripts.map((script, index) => {
              return (
                <Option key={script.key} value={script.name}>
                  {script.name}
                </Option>
              );
            })}
          </Select>
        </Form.Item>
        <Form.Item label="分页">
          每页
          <InputNumber
            style={{ width: '50px' }}
            min={0}
            max={10000}
            defaultValue={10}
            value={this.data.page.pagesize}
            onChange={(event) => {
              this.data.page.pagesize = event;
              this.intSearch(parentForm);
              this.page = this.initPageValue();
              this.refreashData(parentForm);
            }}
          />
          条
        </Form.Item>
      </TabPane>,
    ];
  }

  // 获取表columns信息
  getTableColumns(parentForm) {
    const tableColumns = this.data.columns.map((c, index) => {
      const c2 = {
        title: c.name,
        dataIndex: c.name,
        width: c.widthPercent === 0 ? 'auto' : `${c.widthPercent}%`,
      };
      return c2;
    });
    if (this.data.operators.length > 0) {
      return [...tableColumns, this.getTableOperaters(parentForm)];
    } else {
      return tableColumns;
    }
  }

  // 获取表操作栏信息
  getTableOperaters(parentForm) {
    return {
      title: '操作',
      dataIndex: '操作',
      render: (text, record, index3) => {
        return this.data.operators.map((o, index) => {
          const index2 = `op2:${index}_${o.type}`;
          if (o.type === 'confirm') {
            return (
              <Popconfirm
                key={index2}
                placement="top"
                title={`确认${o.name}?`}
                okText="确认"
                cancelText="取消"
                onConfirm={() => {
                  ApiHelper.postOperator(
                    parentForm.useformData.formkey,
                    o.name,
                    o.url,
                    { key: record.key, id: record.key },
                    (res) => {
                      parentForm.refreash();
                    },
                  );
                }}
              >
                <Button type="link"> {o.name} </Button>
              </Popconfirm>
            );
          } else {
            return (
              <Button
                type="link"
                key={index2}
                onClick={() => {
                  if (o.type === 'openurl') {
                    const w = window.open('_black');
                    w.location.href = o.url.replace('{key}', record.key).replace('{id}', record.key);
                  }
                  if (o.type === 'hrefurl') {
                    window.location.href = o.url.replace('{key}', record.key).replace('{id}', record.key);
                  }
                }}
              >
                {o.name}
              </Button>
            );
          }
        });
      },
    };
  }

  // 表数据刷新
  refreashData(parentForm) {
    if (this.data.dataSource == null || this.data.dataSource === '') {
      this.dataSource = DesignUtil.tryParseJson(this.data.dataSource, []);
    } else {
      const script = parentForm.dataSourceScripts.find((c) => c.name === this.data.dataSource);
      if (script != null) {
        this.loading = true;
        parentForm.refreash();
        parentForm.loadDataSource(
          [script],
          null,
          null,
          (success) => {
            const dataResult = parentForm.dataSourceResults.get(this.data.dataSource);
            if (dataResult != null) {
              this.dataSource = dataResult?.data || [];
              this.page = { ...this.page, ...(dataResult?.page || this.initPageValue()) };
              this.loading = false;
              parentForm.refreash();
            } else {
              this.refreashDataFail(parentForm);
            }
          },
          (fail) => {
            this.refreashDataFail(parentForm);
          },
        );
      }
    }
  }

  refreashDataFail(parentForm) {
    this.dataSource = [];
    this.page = this.initPageValue();
    message.error('表数据加载失败!');
    this.loading = false;
    parentForm.refreash();
  }

  // 渲染搜索栏
  renderSearch(parentForm) {
    return this.data.childControls.map((item, index) => {
      const index2 = `sh:${index}_`;
      if (item.data.childControls && item.data.childControls.length > 0) {
        return <React.Fragment key={index2}> {item.render(parentForm)}</React.Fragment>;
      }
      return <></>;
    });
  }

  // 渲染“筛选”按钮
  renderSearchButton(parentForm) {
    const hasSearch = this.data.childControls.find((c) => c.data.childControls && c.data.childControls.length > 0);
    if (hasSearch != null) {
      return (
        <Button
          onClick={() => {
            this.refreashData(parentForm);
          }}
        >
          筛选
        </Button>
      );
    }
    return <></>;
  }

  getDesignControl(parentForm) {
    return (
      <>
        {this.renderSearch(parentForm)}
        {this.renderSearchButton(parentForm)}
        <Table
          columns={this.getTableColumns(parentForm)}
          rowKey={(record) => record.key}
          dataSource={DesignUtil.dataBind(this.dataSource)}
          pagination={this.page}
          loading={this.loading}
          {...this.extProps}
          onChange={(newPagination, filters, sorter) => {
            this.page = newPagination;
            this.refreashData(parentForm);
            this.extProps?.onChange && this.extProps?.onChange(newPagination, filters, sorter);
          }}
        />
      </>
    );
  }
}

export default TableContainerControl;
